package com.ld.collegetask;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.ld.collegetask.beans.BaseJsonBean;
import com.ld.collegetask.beans.DynamicImgBean;
import com.ld.collegetask.databinding.ActivityDynamicMemberReleaseBinding;
import com.ld.collegetask.serverInterface.RequestSerives;
import com.ld.collegetask.utils.AppApplication;
import com.ld.collegetask.utils.PicassoImageLoader;
import com.ld.collegetask.utils.SharePreference;
import com.squareup.picasso.Picasso;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class DynamicMemberReleaseActivity extends BaseActivity {
    private final String TAG = "DynamicMemberReleaseActivity_1";
    private ActivityDynamicMemberReleaseBinding binding;
    private GalleryConfig galleryConfig;
    private List<String> path = new ArrayList<>();
    private List<String> markeds;
    private Integer userId = 0;
    private MyListAdapter<String> adapter;
    private PromptDialog promptDialog;
    private int biaoji = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dynamic_member_release);
        setTitleView(this, binding.ilTitle, true, true, true, false);
        setTitle("发布说说");
        setText("保存");
        promptDialog = new PromptDialog(this);
        SharePreference sp = new SharePreference(getBaseContext());
        userId = sp.getUserId();
        findView();
        init();
    }

    @Override
    public void loading() {

    }

    public void findView() {
    }

    private void dynamic_member_save(String dcontent, String dphotos) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.dynamic_member_save(userId, dcontent, dphotos);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    Log.e(TAG, "==" + base.getJson());
                    promptDialog.dismiss();
                    Intent it = new Intent(mActivity, MainActivity.class);
                    setResult(1, it);
                    finish();
                } else {
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }


    private String dphotos = "";
    private void dynamic_upload_img(File file) {
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part body =
                MultipartBody.Part.createFormData("pictureFile", file.getName(), requestFile);

        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<ResponseBody> call = requestSerives.dynamic_upload_img(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                String json = "";
                try {
                    json = response.body().source().readString(Charset.forName("UTF-8"));
                    Log.v("Upload",json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(json, BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    DynamicImgBean bean = gson.fromJson(base.getJson(), DynamicImgBean.class);
                    dphotos += bean.getFileUrl()+",";
                    biaoji++;
                    if (markeds.size()>biaoji){
                        dynamic_upload_img(new File(markeds.get(biaoji)));
                    }else {
                        dynamic_member_save(binding.dynamicMemberReleaseDcontent.getText().toString().trim(), dphotos);
                    }
                } else {
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_head_text:
                if (binding.dynamicMemberReleaseDcontent.getText().toString().trim().equals("")){
                    promptDialog.showWarn("请填写说说内容");
                    break;
                }
                hideSoftKeyboard();
                promptDialog.showLoading("正在提交");
                if (markeds.size()>=2) {
                    biaoji = 1;
                    dynamic_upload_img(new File(markeds.get(biaoji)));
                }else {
                    dynamic_member_save(binding.dynamicMemberReleaseDcontent.getText().toString().trim(), "");
                }
                break;
        }
    }

    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
            Log.i(TAG, "onStart: 开启");
        }

        @Override
        public void onSuccess(List<String> photoList) {
            Log.i(TAG, "onSuccess: 返回数据");
            for (String s : photoList) {
                Log.i(TAG, s);
                markeds.add(s);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "onCancel: 取消");
        }

        @Override
        public void onFinish() {
            Log.i(TAG, "onFinish: 结束");
        }

        @Override
        public void onError() {
            Log.i(TAG, "onError: 出错");
        }
    };

    private void init() {
        markeds = new ArrayList<>();
        markeds.add("占位符");
        adapter = new MyListAdapter(this, markeds, R.layout.item_dynamic_member_release_gridview);
        binding.gv.setAdapter(adapter);
        binding.gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == markeds.size() - 1) {
                    galleryConfig = new GalleryConfig.Builder()
                            .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                            .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                            .provider("com.ld.collegetask.fileprovider")   // provider(必填)
                            .pathList(path)                         // 记录已选的图片
                            .multiSelect(true, 4 - markeds.size())                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                            .maxSize(4 - markeds.size())                             // 配置多选时 的多选数量。    默认：9
                            .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                            .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                            .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                            .filePath("/Gallery/Pictures")          // 图片存放路径
                            .build();


                    PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
                                @Override
                                public void permissionGranted(@NonNull String[] permissions) {
                                    if (permissions.length == 2) {
                                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(mActivity);
                                    }
                                }

                                @Override
                                public void permissionDenied(@NonNull String[] permissions) {
                                }
                            }, Manifest.permission.CAMERA
                            , Manifest.permission.WRITE_EXTERNAL_STORAGE
                    );
                }
            }
        });
    }

    public class MyListAdapter<T> extends BaseAdapter {
        private Context context;//上下文环境
        private List<T> list;//通用的，不知道数据
        private int layoutId;//变量的id

        // 通过构造器关联数据源与数据适配器
        public MyListAdapter(Context context, List<T> list, int layoutId) {
            this.context = context;
            this.list = list;
            this.layoutId = layoutId;
        }

        @Override
        public int getCount() {
            if (list != null) {
                if (list.size() == 4) {
                    return 3;
                }
                return list.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Views views;
            if (convertView == null) {
                views = new Views();
                convertView = View.inflate(mActivity, layoutId, null);
                views.imageView = (ImageView) convertView.findViewById(R.id.imageView);
                views.img_x = (ImageView) convertView.findViewById(R.id.img_x);
                convertView.setTag(views);
            } else {
                views = (Views) convertView.getTag();
            }

            RelativeLayout.LayoutParams para1 = (RelativeLayout.LayoutParams) views.imageView.getLayoutParams();
            para1.height = getResources().getDisplayMetrics().widthPixels / 3 / 4 * 3;
            views.imageView.setLayoutParams(para1);
            views.img_x.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    markeds.remove(position + 1);
                    adapter.notifyDataSetChanged();
                }
            });
            if (position == markeds.size() - 1) {
                int resourceId = R.drawable.shuohsuojia;
                Picasso.with(context)
                        .load(resourceId)
                        .fit()
                        .placeholder(R.drawable.shuohsuojia)
                        .error(R.drawable.shuohsuojia)
                        .into(views.imageView);
                views.img_x.setVisibility(View.INVISIBLE);
            } else {
                File file = new File(markeds.get(position + 1));
                Picasso.with(context)
                        .load(file)
                        .fit()
                        .placeholder(R.mipmap.gallery_pick_photo)
                        .error(R.mipmap.gallery_pick_photo)
                        .into(views.imageView);
                views.img_x.setVisibility(View.VISIBLE);
            }
            return convertView;
        }

        class Views {
            public ImageView imageView;
            public ImageView img_x;
        }
    }

}
